const User = require('../model/user.model')
const Question = require('../model/question.model')
const Result = require('../model/result.model')
const bcrypt = require('bcryptjs')
const md5 = require('blueimp-md5')
const Tag = require('../model/tag.model')

const createUser = async (password) => {
  const salt = bcrypt.genSaltSync(10)
  // 000000
  const hash = bcrypt.hashSync(md5(password), salt)
  User.create({ username: 'visitor', password: hash }, { ignoreDuplicates: true })
}

async function updateModel() {
  await User.sync({ alter: true })
  createUser('000000')
  console.log('更新Users model成功')
  await Tag.sync({ alter: true })
  console.log('更新Tags model成功')
  await Question.sync({ alter: true })
  console.log('更新Questions model成功')
  await Result.sync({ alter: true })
  console.log('更新Result model成功')
}

async function reloadModel() {
  await Result.drop()
  console.log('删除Result model成功')
  await Question.drop()
  console.log('删除Questions model成功')
  await Tag.drop()
  console.log('删除Tag model成功')
  await User.drop()
  console.log('删除Users model成功')
}

const arguments = process.argv.splice(2)
if (arguments[0] === 'update') {
  updateModel()
} else if (arguments[0] === 'reload') {
  (async () => {
    await reloadModel()
    await updateModel()
  })()
} else {
  console.error('Error: 未知的命令')
}

// yarn model update
// yarn model reload
